<template>
  <view class="settle-box">
    <!-- 全选按钮 -->
    <view class="all-btn">
      <radio
        :checked="toBeSelected"
        color="red"
        @click="setBeSelectedAll(!toBeSelected)"
      >
        全选
      </radio>
    </view>
    <!-- 总价格 -->
    <view class="price-text">
      合计:
      <text class="price-text-price">¥ {{ goodsTotalAmount }}</text>
    </view>
    <!-- 结算按钮 -->
    <view class="settlement-btn">
      <button type="warn" @click="submitSettlement">
        结 算({{ selGoodsCount }})
      </button>
    </view>
  </view>
</template>

<script>
import { mapGetters, mapMutations, mapState } from 'vuex'
export default {
  name: 'my-settle',
  data() {
    return {}
  },
  computed: {
    ...mapGetters('cart', {
      selGoodsCount: 'selGoodsCount', //商品被选中数量
      total: 'total', //商品总数量,
      goodsTotalAmount: 'goodsTotalAmount' //结算总金额
    }),
    ...mapState('user', {
      token: 'token',
      address: 'address',
      userinfo: 'userinfo'
    }),
    ...mapState('cart', {
      cart: 'cart'
    }),
    toBeSelected() {
      //所有商品是否被选中
      return this.selGoodsCount === this.total
    }
  },
  methods: {
    ...mapMutations('cart', {
      setBeSelectedAll: 'setBeSelectedAll'
    }),
    //结算
    async submitSettlement() {
      //商品是否有一件被选中
      if (!this.selGoodsCount) {
        uni.showToast({
          title: `选中商品后结算`,
          icon: 'none'
        })
        return
      }
      //地址是否存在
      if (JSON.stringify(this.address) === '{}') {
        uni.showToast({
          title: `请先选择地址后下单`,
          icon: 'none'
        })
        return
      }
      //用户是否登录
      if (!this.token || JSON.stringify(this.userinfo) === '{}') {
        const [err, res] = await uni.showModal({
          title: '提示',
          content: '登陆后才能下单，您要去登录吗？'
        })
        // confirm	Boolean	为 true 时，表示用户点击了确定按钮
        // cancel	Boolean	为 true 时，表示用户点击了取消
        if (res.confirm) {
          //  跳转到 my 页面
          uni.switchTab({
            url: '/pages/my/my'
          })
        }
        return
      }
      // 4. 实现微信支付功能
      this.payOrder()
    },
    // 微信支付
    async payOrder() {
      // 1. 创建订单
      // 1.1 组织订单的信息对象
      const address = this.address
      const useraddres = `${address.provinceName}${address.cityName}${
        address.countyName
      }${address.detailInfo}`
      const orderInfo = {
        // 开发期间，注释掉真实的订单价格，
        // order_price:,
        // 写死订单总价为 1 分钱
        order_price: 0.01,
        consignee_addr: useraddres,
        goods: this.cart
          .filter(x => x.goods_state)
          .map(x => ({
            goods_id: x.goods_id,
            goods_number: x.goods_count,
            goods_price: x.goods_price
          }))
      }
      // 1.2 发起请求创建订单
      const { data: res } = await uni.$http.post(
        '/api/public/v1/my/orders/create',
        orderInfo
      )
      if (res.meta.status !== 200) return uni.$showToast('创建订单失败!')
      // 1.3 得到服务器响应的“订单编号”
      const orderNumber = res.message.order_number
      // 2. 订单预支付
      const { data: pay } = await uni.$http.post(
        '/api/public/v1/my/orders/req_unifiedorder',
        {
          order_number: orderNumber
        }
      )
      if (pay.meta.status !== 200) return uni.$showToast('创建订单失败!')
      const payInfo = pay.message.pay
      // 3. 发起微信支付
      const { err, data } = await uni.requestPayment(payInfo)
      if (err) return uni.showToast('订单未支付')
      const { data: payStatus } = await uni.$http.post(
        '/api/public/v1/my/orders/chkOrder',
        {
          order_number: orderNumber
        }
      )
      if (payStatus.meta.status !== 200) return uni.$showToast('订单未支付!')
      uni.showToast('支付成功！')
    }
  }
}
</script>

<style lang="scss">
.settle-box {
  height: 50px;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  border-top: 1px solid #efefef;
  z-index: 999;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  padding-left: 5px;
  box-sizing: border-box;
  .price-text {
    .price-text-price {
      color: red;
    }
  }
  .settlement-btn {
    height: 50px;
    min-width: 120px;
    text-align: center;
    button {
      height: 100%;
      font-size: 16px;
      line-height: 50px;
      border-radius: 0;
      border: none;
    }
  }
}
</style>
